package blog.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.PageInfo;
import com.service.ArticleService;
import com.service.CategoryService;
import com.service.TagService;

import blog.entity.Article;
import blog.entity.Category;
import blog.entity.Tag;
import blog.entity.User;
import cn.hutool.http.HtmlUtil;

@Controller 
@RequestMapping("/admin/article")
public class ArticleController {
	
	//文章相关业务层实现对象
	@Autowired
	private ArticleService articleService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private TagService tagService;
	/**
	 * 	展示全部文章
	 * @param pageIndex		分页-->当前页
	 * @param pageSize		分页-->页面大小
	 * @param model			用来传值			
	 * @return   			视图
	 */
	@RequestMapping("")
	public String allArticle(
			@RequestParam(required=false,defaultValue="1") Integer pageIndex,
			@RequestParam(required=false,defaultValue="10")  
			Integer pageSize,  Map<String,Object> model) {
		
		//得到文章列表
		PageInfo<Article> articePageInfo= articleService.getPageArticleList(pageIndex,pageSize);
		
		//把前缀数据传给分页页面
		model.put("pageUrlPrefix", "admin/article?pageIndex");  
		//将页面集合传递给 article-list 页面
		model.put("pageInfo",articePageInfo);
		return "Article/article-list";
	}
	/**
	 * 	添加草稿
	 * @param articleTitle 标题
	 * @param articleContent 内容
	 */
	@RequestMapping("/insertDraftSubmit")
	private String insertDraftSubmit(String articleTitle,String articleContent) {
		System.out.println("xxxx11");
		Article article = new Article();
		article.setArticleTitle(articleTitle);
		article.setArticleContent(articleContent);
		articleService.insertDraftSubmit(article);
		//等于重新登录，，，临时赶工的粗糙做法
		return "forward:/user/login?userName=root&userPass=root";
	}
	/**
	 * 	去写文章的界面
	 * @return
	 */
	@RequestMapping(value = "/insert",method=RequestMethod.GET )
	private String goInsert(Map<String,Object> model) {
		//分类列表
		List<Category> categoryList=categoryService.listCategory();
			
	    //标签列表
	    List<Tag> tagList=tagService.listTag();

	    model.put("categoryList", categoryList);
	    model.put("tagList",tagList);
	    
		
		return "Article/article-add";
	}
	/**
	 * 
	 * @param article	文章实体类，包含了前端传递的  文章标题、文章内容、文章状态(草稿,或发布)
	 * @param request   获取Session,以及前端传过来的一级分类id和二级分类id
	 * @return
	 */
	@RequestMapping(value ="/insert",method=RequestMethod.POST )
	public String add(Article article,HttpServletRequest request) {
		
		//当前用户的id
		User user=(User)request.getSession().getAttribute("session_user");
		System.err.println(user);
		article.setArticleUserId(user.getUserId());
		
		//文章摘要 HtmlUtil是 hutu 工具包提供的一个类
		String s= HtmlUtil.cleanHtmlTag(article.getArticleContent());
		article.setArticleSummary(s.length()>150?s.substring(0,150):s);

		//文章的一些初始默认值
		//回复次数
		article.setArticleCommentCount(0);
		//喜欢次数
		article.setArticleLikeCount(0);
		//浏览次数
		article.setArticleViewCount(0);
		//默认的排序
		article.setArticleOrder(1);
		//是否回复
		article.setArticleIsComment(0);
		//文章发布时间,修改时间。默认为当前时间
		article.setArticleCreateTime(new Date());
		article.setArticleUpdateTime(new Date());
		
		//一级分类ID
		int parentCateId =Integer.parseInt(request.getParameter("articleParentCategoryId"));
		//二级分类ID
		int childCateId=Integer.parseInt(request.getParameter("articleChildCategoryId"));
		
		//标签
		String [] tagIds =request.getParameterValues("articleTagIds");
		
		//把分类信息 交给article
		List<Category>categoryList=new ArrayList<>(2);
		categoryList.add(new Category(parentCateId));
		categoryList.add(new Category(childCateId));
		article.setCategoryList(categoryList);
		
		//把标签信息,交给article
		List<Tag> tagList=new ArrayList<>();
		for(String tagId:tagIds) {
			tagList.add(new Tag(Integer.parseInt(tagId)));
		}
		article.setTagList(tagList);
		
		//调用业务层,进行文章发布
		articleService.addArticle(article);
		
		//forward 或  redirect 不受前后缀的影响
		return "forward:/admin/article";
	}
	/**
	 * 	上传图片
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/uploadImg")  //实际上由于返回的数据已经是JSON格式了,所以这里可以不用  @ResponseBody
	public String upload(MultipartHttpServletRequest request) throws Exception {
		//imgFile 这个名称是固定的
		MultipartFile file =request.getFile("imgFile");
		
		//生成一个随机的文件名
		String newName=UUID.randomUUID().toString()+".jpg";
		File destFile=new File("D:/apche8.5/apache-tomcat-8.5.49/imguploads/"+newName);
		
		String path="http://localhost:8080/uploads/"+ newName;
		
		file.transferTo(destFile);
		
		return "{\"error\":0,\"url\":\""+path+"\"}" ;
		
	}
	/**
	 * 	去文章修改界面
	 * @param articleId
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/edit/{articleId}",method =RequestMethod.GET )
	private String goEdit(@PathVariable int articleId,Map<String,Object> model) {

		//文章信息
		Article article = articleService.getArticleById(articleId);
		// 分类列表
		List<Category> categoryList = categoryService.listCategory();
		// 标签列表
		List<Tag> tagList = tagService.listTag();
		
		System.err.println(article);

		model.put("categoryList", categoryList);
		model.put("tagList", tagList);
		model.put("article", article);
		
		return "Article/article-edit";
	}
	/**
	 * 	执行修改操作
	 * @param articleId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/edit" ,method =RequestMethod.POST)
	private String edit(Article article,HttpServletRequest request) {
		
		//更新修改时间为当前时间
		article.setArticleUpdateTime(new Date());
		//文章摘要 HtmlUtil是 hutu 工具包提供的一个类
		String s = HtmlUtil.cleanHtmlTag(article.getArticleContent());
		article.setArticleSummary(s.length() > 150 ? s.substring(0, 150) : s);
		//一级分类ID
		int parentCateId =Integer.parseInt(request.getParameter("articleParentCategoryId"));
		//二级分类ID
		int childCateId=Integer.parseInt(request.getParameter("articleChildCategoryId"));
		//标签
		String[] tagIds = request.getParameterValues("articleTagIds");

		// 把分类信息 交给article
		List<Category> categoryList = new ArrayList<>(2);
		categoryList.add(new Category(parentCateId));
		categoryList.add(new Category(childCateId));
		article.setCategoryList(categoryList);

		// 把标签信息,交给article
		List<Tag> tagList = new ArrayList<>();
		for (String tagId : tagIds) {
			tagList.add(new Tag(Integer.parseInt(tagId)));
		}
		article.setTagList(tagList);
		
		System.err.println("修改后的"+article);
		
		//调用业务层,进行文章修改
		articleService.updateArticle(article);
		
		return "forward:/admin/article";
	}
	/**
	 * 	文章删除操作,由于是AJAX请求,且回调函数不需要接受参数,所以目前不需要返回值
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
	@ResponseBody
	private String delete(@PathVariable Integer id) {
		System.err.println("要删除的文章的id为:"+id);
		//执行删除
		articleService.deleteArticleById(id);
		return "";
	}
}
